import {onBeforeMount, onMounted, ref} from 'vue'
import goodStorage from 'good-storage'
import { CodeHistory } from '@/types/code'

const POST_CODE_TEMP_KEY = '_post_code_temp'
const BROWSING_HISTORIES_KEY = '_browsing_histories'
const FAVORITE_MODES_KEY = '_favorite_modes'
const FAVORITE_THEMES_KEY = '_favorite_themes'

const browsingHistoryLimit = 30
const modeAndThemeLimit = 8

export default function(func?:()=>Promise<any>) {
  const browsingHistories = ref<Array<CodeHistory>>([])
  const codeTemp = ref()
  const modeHistories = ref<Array<any>>([])
  const themeHistories = ref<Array<string>>([])

  codeTemp.value = goodStorage.get(POST_CODE_TEMP_KEY, null)
  browsingHistories.value = goodStorage.get(BROWSING_HISTORIES_KEY, [])
  modeHistories.value = goodStorage.get(FAVORITE_MODES_KEY, [])
  themeHistories.value = goodStorage.get(FAVORITE_THEMES_KEY, [])

  const setHistoryMode = (mode: any) => {
    if (!mode){
      return
    }
    const newModes = modeHistories.value.filter(item=>item.name !== mode.name)
    newModes.unshift(mode)
    modeHistories.value = newModes.slice(0, modeAndThemeLimit)
    goodStorage.set(FAVORITE_MODES_KEY, modeHistories.value)
  }

  const setHistoryTheme = (theme: string) => {
    if (!theme){
      return
    }
    const newThemes = themeHistories.value.filter(item=>item !== theme)
    newThemes.unshift(theme)
    themeHistories.value = newThemes.slice(0, modeAndThemeLimit)
    goodStorage.set(FAVORITE_THEMES_KEY, themeHistories.value)
  }

  const setCodeTemp = (value: any) => {
    goodStorage.set(POST_CODE_TEMP_KEY, value)
  }
  const removeCodeTemp = () => {
   goodStorage.remove(POST_CODE_TEMP_KEY)
  }
  const browsingHistoryPush = (item: CodeHistory) => {
    setHistory(item)
  }

  const findHistoryIndex = (id: string) => {
    return browsingHistories.value.findIndex((item: CodeHistory) => item.id === id)
  }

  const setHistory = (item: CodeHistory) => {
    item.updateTime = Date.now()
    const limit = browsingHistoryLimit
    const histories =  browsingHistories
    const key = BROWSING_HISTORIES_KEY
    const historyIndex = findHistoryIndex(item.id)
    if (historyIndex !== -1) {
      histories.value.splice(historyIndex, 1)
    }
    histories.value.unshift(item)
    histories.value = histories.value.slice(0, limit)
    goodStorage.set(key, histories.value)
  }
  const setBrowsingStorage = ()=>{
    goodStorage.set(BROWSING_HISTORIES_KEY, browsingHistories.value)
  }
  const removeBrowsingHistory = (id: string) => {
    if (!id){
      browsingHistories.value = []
    }else {
      const index = findHistoryIndex(id)
      if (index !== -1){
        browsingHistories.value.splice(index, 1)
      }
    }
    setBrowsingStorage()
  }
  return {
    setHistoryMode,
    setHistoryTheme,
    modeHistories,
    themeHistories,
    browsingHistoryPush,
    browsingHistories,
    codeTemp,
    setCodeTemp,
    removeCodeTemp,
    removeBrowsingHistory
  }
}
